package gjwt

import (
	"github.com/golang-jwt/jwt/v4"
	"time"
)

var signingKey = []byte("wx:ywdoing")

type Claims struct {
	Data Data
	jwt.RegisteredClaims
}
type Data struct {
	Uid      int    `json:"uid"`
	Role     string `json:"role"`
	Pid      int    `json:"pid"`
	Acid     int    `json:"acid"`
	GoodsId  int    `json:"goods_id"`
	GoodsIds string `json:"goods_ids"`
	Url      string `json:"url"`
}

func Parse(tokenString string) (*Data, error) {
	token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return signingKey, nil
	})
	if claims, ok := token.Claims.(*Claims); ok && token.Valid {
		return &claims.Data, nil
	} else {
		return nil, err
	}
}

func Build(data Data, expireSecond int64) (string, error) {
	claims := Claims{
		data,
		jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(expireSecond) * time.Second)),
			Issuer:    "ywdoing",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString(signingKey)
	if err != nil {
		return "", nil
	}
	return ss, nil
}
